<template>
	<view class="category">
		<view class="row add" @click="clickAdd">
			<view class="left">
				<u-icon name="plus" size="22" color="#576b9f"></u-icon>
				<text class="text">新增分类</text>
			</view>
		</view>
		<view class="row" v-for="(item,index) in categoryList" :key="item._id">
			<view class="left">{{item.name}}</view>
			<view class="right">
				<u-icon name="edit-pen" size="26" color="#576b9f" @click="updateData(item._id,item.name)"></u-icon>
				<u-icon name="trash" size="26" color="#ec544f" @click="deleteData(item._id)"></u-icon>
			</view>
		</view>

		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog ref="inputClose" mode="input" title="分类名称" :value="inputValue" placeholder="请输入分类名称"
				@confirm="dialogInputConfirm"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	const db=uniCloud.database();
	export default {
		data() {
			return {
				inputValue:"",
				categoryList: [],
				updateId:null
			};
		},
		onLoad() {
			this.getCategoryList(); 
		},
		methods:{
			getCategoryList(){
				db.collection("mall-categories").get().then(res=>{
					//console.log(res);
					this.categoryList=res.result.data;
				})	
			},			
			clickAdd(){
				this.inputValue="";
				this.updateId=null;
				this.$refs.inputDialog.open();
			},
			async dialogInputConfirm(e){
				this.inputValue=e;
		
				if(this.updateId){
					await db.collection("mall-categories").doc(this.updateId).update({
						name:this.inputValue
					})
				}else{
					await db.collection("mall-categories").add({
						name:this.inputValue
					})
				}
				this.getCategoryList();
				
			
				this.inputValue="";	
			},
			deleteData(id){
				uni.showModal({
					content:"是否删除该分类？",
					success: res=> {
						if(res.confirm){
							db.collection("mall-categories").doc(id).remove().then(res=>{
								this.getCategoryList();
							})
						}
					},
					fail: res => {
						console.log(res);
					}
				})
			},
			updateData(id,name){
				this.inputValue=name;
				this.updateId=id;
				this.$refs.inputDialog.open();
			}
		}
		
	}
</script>

<style lang="scss" scoped>
	.category {
		padding: 30rpx;

		.row {
			@include flex-box();
			border-bottom: 1px solid $border-color-light;
			padding: 26rpx 0;

			.left {
				font-size: 34rpx;
			}

			.right {
				@include flex-box();

				.u-icon {
					margin-left: 30rpx;
				}
			}
		}

		.row.add {
			.left {
				color: $brand-theme-color-aux;
				@include flex-box();

				.text {
					font-size: 34rpx;
					margin-left: 10rpx;
				}
			}
		}
	}
</style>